const net = require('net');
const path = require("path");
const log = require(path.resolve(__dirname, '../../../tool/log/log'));

/**
* Tcp
*/

class Tcp{
    
    constructor(serverConf = {}){
        const Server = net.createServer();
        this.sockets = new Map();
        this.skCb = () => {};
        // tcp socket 
        Server.on('connection', (sk) => {
            // callback
            this.skCb(sk, this.sockets);
 
            // socket close remove
            sk.on('close', () => {
                this.sockets.delete(sk);
            });

            // socket error
            sk.on('error', (err) => {
                log.error.error(err);
            });
        });


        // tcp error event
        Server.on('error', (err) => {
            log.error.error('tcp socket server');
            log.error.error(err);
        }); 

        // start listen
        Server.listen(serverConf, () => {
            console.log('tcp socket server start');
        });  
    }
    getSk(cb = () => {}){
        this.skCb = cb;
    }
}
module.exports = Tcp;
